package com.dingpeikeji.quickdeer.modules.wx.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.modules.line.entity.TLine;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.wx.base.web.WxCommonController;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.CookieUtils;
import com.dingpeikeji.quickdeer.utils.JsonUtils;
import com.dingpeikeji.quickdeer.utils.StringUtil;

@Controller
@RequestMapping("/wx/rentproduct")
public class WRentproductController {
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private FRealscheService fRealscheService;

	// 旅游线路
	@RequestMapping(value = "/getTravelList")
	public String travelList(TRentproduct tRentproduct, TRentgroup tRentgroup, HttpServletRequest request,
			HttpServletResponse response, String pageNo, String pageSize, Model model, String destination,
			String estday) throws Exception {
		// 根据sitenam查询对应的siteid
		TSitedtl tSitedtl = tSitedtlService.get(tRentproduct.getDepartcity().getSiteid());
		tRentgroup = initParam(tRentgroup, tRentproduct);// 初始化周边游,目的地游
		tRentgroup.setDepartcity(tSitedtl);
		if (destination.contains("不限")) {
			destination = null;
		}
		tRentgroup.setDestination(destination);
		tRentgroup.setSitename(tRentproduct.getDepartcity().getSitename());
		tRentgroup.setSiteid(tRentproduct.getDepartcity().getSiteid());
		String day = request.getParameter("estday");
		if ("0".equals(estday) || estday.contains("不限") || StringUtils.isEmpty(estday)) {
			tRentgroup.setDaysnum(null);
		} else {
			tRentgroup.setDaysnum(Integer.parseInt(estday.substring(0, 1)));
			model.addAttribute("day", Integer.parseInt(day.substring(0, 1)));
		}
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 查询天数
		List<Integer> dayList = tRentgroupService.getTravelProductDaysNum(tRentgroup);
		model.addAttribute("dayList", dayList);
		// 查询包含的景点
		Set<String> allSiteList = new TreeSet<String>();
		List<String> siteList = tRentgroupService.getTravelSiteList(tRentgroup);
		for (String sites : siteList) {
			String[] arr = sites.split("-");
			for (int i = 0; i < arr.length; i++) {
				allSiteList.add(arr[i]);
			}
		}
		model.addAttribute("destination", destination);
		model.addAttribute("allSiteList", allSiteList);
		// 分页查询
		Page<TRentgroup> page = new Page<TRentgroup>(request, response);
		tRentgroup.setPage(page);
		if (StringUtils.isEmpty(pageSize) || StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
			pageSize = "4";
		}
		page.setPageNo(Integer.parseInt(pageNo));
		page.setPageSize(Integer.parseInt(pageSize));
		List<TRentgroup> rentGroupList = tRentgroupService.getMobileTravelProducts(tRentgroup);
		//无论是否有数据,都要返回
		model.addAttribute("tRentgroup", tRentgroup);
		model.addAttribute("tRentproduct", tRentproduct);
		// 没有查询到线路
		if (rentGroupList.size() == 0 || rentGroupList == null) {
			return "/wx/modules/travelProduct/travelResult";
		}
		page.setList(rentGroupList);
		// 查询线路对应的产品
		for (TRentgroup tr : rentGroupList) {
			tRentproduct.setDepartcity(tr.getDepartcity());
			tRentproduct.setDestcity(tr.getDestcity());
			tRentproduct.setProductname(tr.getProductname());
			tRentproduct.setRentType(tr.getRenttype());
			double lowestPrice = rentproductService.findLowestPrice(tRentproduct);
			tr.setLowestPrice(lowestPrice);
		}
		model.addAttribute("page", page);
		model.addAttribute("rentGroupList", rentGroupList);
		return "/wx/modules/travelProduct/travelResult";
	}

	private TRentgroup initParam(TRentgroup tRentgroup, TRentproduct tRentproduct) {
		if (tRentproduct.getTabType().contains("周边游包车")) {
			tRentproduct.setTabType("周边游包车");
			tRentproduct.setAnothertabType("目的地包车");
			tRentgroup.setTraveltype(1);
		} else if (tRentproduct.getTabType().contains("目的地包车")) {
			tRentproduct.setTabType("目的地包车");
			tRentproduct.setAnothertabType("周边游包车");
			tRentgroup.setTraveltype(2);
		} else {
			tRentgroup.setTraveltype(1);
			tRentproduct.setTabType("周边游包车");
			tRentproduct.setAnothertabType("目的地包车");
		}
		return tRentgroup;
	}

	@RequestMapping("getTravelDetail")
	public String travelDetails(TRentproduct tRentproduct, Model model, TCargotype tCargotype, TRentgroup tRentgroup,
			TLine tLine, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取线路描述
		String description = tRentgroupService.getDescriptionById(tLine.getLinename());
		description = description.replaceAll("&nbsp;", "");
		tRentgroup.setDescription(description);
		String[] arr = description.split("第" + "\\S" + "天");
		Map<Long, String> map = new HashMap<Long, String>();
		List<Long> list = formatDesc(arr, map);
		model.addAttribute("map", map);
		model.addAttribute("tLine", tLine);
		return "wx/modules/travelProduct/travelDetail";
	}

	private List<Long> formatDesc(String[] arr, Map<Long, String> map) {
		// el表达式中数字1是Long类型，无法匹配后台map中的int。
		// 修改 map.put(0L, value); 前台 ：${map[1]}.
		List<Long> list = new ArrayList<Long>();
		long i = 1;
		for (String s : arr) {
			if (StringUtils.isEmpty(s) || s.length() == 0 || "".equals(s)) {
				continue;
			}
			map.put(i, s.substring(1).replaceAll(" {2,}", ""));// X{n,} X，至少 n 次
			i++;
			list.add(i);
		}
		return list;
	}

	@RequestMapping("travelBook")
	public String travelBook(TRentproduct tRentproduct, String pageNo, String pageSize, Model model,
			TCargotype tCargotype, TRentgroup tRentgroup, TLine tLine, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		// 获取车型
		String tstyle = request.getParameter("tstyle");
		tCargotype.setTstyles(tstyle);
		tRentproduct.setCargotype(tCargotype);
		// 初始化TRentproduct
		tRentproduct.getDepartcity().setSiteid(tRentproduct.getDepartcity().getId());
		tRentproduct.getDestcity().setSiteid(tRentproduct.getDestcity().getId());
		tRentproduct.setProductname(tLine.getLinename());
		// 初始化tcargotype
		tCargotype.getDepartcity().setSiteid(tRentproduct.getDepartcity().getId());
		tCargotype.getDestcity().setSiteid(tRentproduct.getDestcity().getId());
		tCargotype.setProductname(tLine.getLinename());
		// 分页对象
		Page<TCargotype> page = new Page<TCargotype>(request, response);
		page.setPageNo(Integer.parseInt(pageNo));
		page.setPageSize(Integer.parseInt(pageSize));
		tCargotype.setPage(page);
		// 查询线路所拥有的车型
		List<TCargotype> cargotypeList = rentproductService.getCargotypeList(tCargotype);
		if (cargotypeList == null || cargotypeList.size() == 0) {
			return "wx/modules/travelProduct/travelResult_car";
		}
		page.setList(cargotypeList);
		tRentproduct.setCargotypeList(cargotypeList);
		// 获取车型id,查询对应的线路报价
		List<TRentproduct> rentproductList = null;
		if (cargotypeList.size() > 0) {
			for (TCargotype tc : cargotypeList) {
				tRentproduct.setCargotype(tc);
				rentproductList = rentproductService.findTravelMobileList(tRentproduct);
				tc.setRentproductList(rentproductList);
			}
		}
		// 整车查询列表
		model.addAttribute("cargotypeList", cargotypeList);
		return "wx/modules/travelProduct/travelResult_car";
	}
	
	// 订单填写
	@RequestMapping("travelBooking")
	public String genOrderDetails(TRentproduct tRentproduct, Model model, HttpServletRequest request)
			throws Exception {
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.getMobileRentgroup(rentproduct.getRentgrpid());
		if (rentproduct == null || rentgroup == null) {
			return "wx/modules/travelProduct/travelBook";
		}
		// 协议价逻辑处理
		TRentproduct query = new TRentproduct();
		query.setRentid(tRentproduct.getRentid());
		query.setDepartdate(new Date());
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(query, request, "f");
		query = rentproductService.getSuitrtnprice(query);
		rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		model.addAttribute("tRentproduct", rentproduct);
		model.addAttribute("rentgroup", rentgroup);
		WxCommonController.defaultTime(model, request);
		return "wx/modules/travelProduct/travelBook";
	}
}
